package network;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 东莞呵呵
 * Date:2022-10-05
 * Time:19:37
 */
public class UdpEchoClient {
    private String IP;
    private int post;
    private DatagramSocket socket = null;

    public UdpEchoClient(String IP, int post) throws SocketException {
        socket = new DatagramSocket();
        this.IP = IP;
        this.post = post;
    }

    public void start() throws IOException {
        //1、构造请求
        System.out.print("-> ");
        Scanner in = new Scanner(System.in);
        String request = in.next();
        DatagramPacket requestPacket = new DatagramPacket(request.getBytes(), request.getBytes().length, InetAddress.getByName(IP), post);
        //2、发往服务器
        socket.send(requestPacket);
        //3、接受响应
        DatagramPacket responsePacket = new DatagramPacket(new byte[1024], 1024);
        //接收型参数
        socket.receive(responsePacket);
        String response = new String(responsePacket.getData(), 0, responsePacket.getLength(), "UTF-8");

        //4、输出响应
        System.out.println("响应: "+response);
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient("127.0.0.1",9090);
        client.start();
    }
}
